import { createSlice } from '@reduxjs/toolkit';
import { getUserInfoThunk } from '@/redux/thunks/user'

interface IUserState {
  userInfo: IUserInfo | null;
  token: string,
  memu?: any[]
}

interface IUserInfo {
  routes: string[];
  buttons: string[];
  username: string;
}

const initialState: IUserState = {
  userInfo: null,
  token: localStorage.token,
  memu: []
};

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    setUserInfo: (state: IUserState, { payload }) => {
      state.userInfo = payload
    },
    setToken: (state: IUserState, { payload }) => {
      state.token = payload
      localStorage.setItem('token', payload)
    },
    logout: (state: IUserState) => {
      state.token = ''
      localStorage.removeItem('token')
    },
    setMenu: (state: IUserState, { payload }) => {
      console.log(payload)
      state.memu = payload
    }
  },
  extraReducers: (builder) => {
    builder.addCase(getUserInfoThunk.fulfilled, (state, action) => {
      state.userInfo = action.payload || null;
    });
  }
});


export const { setUserInfo, setToken, setMenu, logout } = userSlice.actions;

export default userSlice.reducer;

export type { IUserState }